/*
 * NotEmptyValidator.java
 * 
 * Created on 22-Aug-2007, 19:13:22
 * 
 * Copyright (C)
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the License, or (at your option) any later
 * version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple
 * Place, Suite 330, Boston, MA 02111-1307 USA
 */

package com.grubby.databean.constraints.validation;

import com.grubby.databean.constraints.annotation.NotEmpty;
import java.lang.annotation.Annotation;

/**
 * A validator for the {@link NotEmpty NotEmpty} constraint.
 * @see NotEmpty
 *
 * @author A. HARMEL-LAW. E: andrew.harmel.law@gmail.com
 * @version 0.1
 */
public class NotEmptyValidator extends AbstractConstraintValidator {

    /**
     * Constructs a NoEmptyValidator object.
     */
    // suppress the unchecked warning for unchecked generic array creation
    @SuppressWarnings("unchecked")
    public NotEmptyValidator() {
        super(NotEmpty.class);
    }

    public ConstraintViolation validate(Object objValue, 
            Annotation constraint) {
        
        ensureConstraintIsSupported(constraint);

        NotEmpty mi = (NotEmpty) constraint;
        ConstraintViolation result = null;

        if (objValue == null) {
            result = new ConstraintViolation(mi,
                "NotEmpty constraint violated. The String provided was null.");
        } else {
            if (!(objValue instanceof String))
                throw new IllegalArgumentException("NotEmptyValidator was "
                        + "passed a value that was not an instance String");
    
            /*
             * Convert the number to a double and then compare with the 
             * constraints value.
             * Note the conversion to double may result in the loss of 
             * information for values of type long.
             */
            String value = (String)objValue;
            if (value.length() == 0) {
                result = new ConstraintViolation(mi,
                    "NotEmpty constraint violated. Value " + value + " is empty");
            }
        }

        return result;
    }
}

